#!/bin/bash
########################################################################
# script name:  host_config.sh
# Used for:
# Author:       Martin Dumont
# Contributors:
# Version:      0.1
#
# (date format: date +'%Y/%m/%d')
#
# Date          Version Contributors    Modifications
# ----------    ------- ------------    -------------
# 2012/05/15    0.1     MDUMONT         initial
########################################################################
usage()
{
cat << STOP

usage: $0 [options] [ARG]

This script is used for ....

OPTIONS:
   -f               Load file
   -d               Dump table
   -r               Restore table from a dump file

Ex.:
$0 -f /tmp/loadfile
$0 -r /central/logs/tmp/hostconfig_2012-06-29-10-20.dump
$0 -d > /central/logs/tmp/hostconfig_`date +'%Y-%m-%d-%H-%M'`.dump
STOP
}
#######################################
# Get parameters
#######################################
ACTION=dump
while getopts f:dr: OPTION
do
	case $OPTION in
		f)
			ACTION=file
			FILE=$OPTARG
			if [ ! -f "$FILE" ]; then echo "File \"$FILE\" doesn't exist"; exit 1; fi				
			;;
		r)
			ACTION=restore
			FILE=$OPTARG
			if [ ! -f "$FILE" ]; then echo "File \"$FILE\" doesn't exist"; exit 1; fi				
			;;
		d)
			ACTION=dump
			;;
		\?)
			usage
			exit 1
			;;
		*)
			usage
			exit 1
			;;
	esac
done
if [ $OPTIND = 1 ]; then usage; exit 1; fi
#######################################
# Variables and environnement
#######################################
BAENV=$(dirname `which $0`)/loadenv.sh
if [ -f $BAENV ]; then . $BAENV; else echo "No env library ($BAENV)"; exit 1; fi
#######################################
# MAIN
#######################################
if [ `whoami` != root ]; then echo Please run this script as root or using sudo; exit; fi
case $ACTION in
	dump)
		sudo -u saunix /opt/freeware/bin/mysql/mysqldump opmgt hostconfig
	;;
	file)
		read -n 1 -p "Do you want to truncate the whole table opmgt.hostconfig? [y/n] "
		/bin/echo
		if [ "$REPLY" = "y" ]; then sudo -u saunix /opt/freeware/bin/mysql/mysql -v -e "TRUNCATE opmgt.hostconfig;"; fi
		while IFS=: read SERVER OS ENVIR SID ANF MAINT PHY HACMP SAP ORA COMMENT
		do
			QUERY="REPLACE INTO opmgt.hostconfig (server,os,env,sid,brbackup,maint,physical,hacmp,sap,ora,comment) \
			VALUES ('$SERVER','$OS','$ENVIR','$SID','$ANF','$MAINT','$PHY','$HACMP','$SAP','$ORA','$COMMENT');"
			sudo -u saunix /opt/freeware/bin/mysql/mysql -v -e "$QUERY"
		done < <(cat $FILE | grep -v '^#' | grep .)
	;;
	restore)
		sudo -u saunix /opt/freeware/bin/mysql/mysql -v -e "TRUNCATE opmgt.hostconfig;"
		sudo -u saunix /opt/freeware/bin/mysql/mysql -v opmgt < $FILE
	;;
esac
exit
